<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="项目经理" prop="managerId" v-if="isProjectAdmin">
        <el-select v-model="queryParams.managerId" clearable placeholder="请选择项目经理">
          <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入名称" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select v-model="queryParams.category" clearable placeholder="请选择类别">
          <el-option v-for="dict in dict.type.moe_project_category" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-select v-model="queryParams.level" clearable placeholder="请选择级别">
          <el-option v-for="dict in dict.type.moe_project_level" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="queryParams.startTime" clearable placeholder="请选择开始时间" type="date"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="截止时间" prop="endTime">
        <el-date-picker v-model="queryParams.endTime" clearable placeholder="请选择截止时间" type="date"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="项目状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择项目状态">
          <el-option v-for="dict in dict.type.moe_project_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-has-permi="['system:project:add']" icon="el-icon-plus" plain size="mini" type="primary"
          @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-has-permi="['system:project:edit']" :disabled="single" icon="el-icon-edit" plain size="mini"
          type="success" @click="handleUpdate">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-has-permi="['system:project:remove']" :disabled="multiple" icon="el-icon-delete" plain size="mini"
          type="danger" @click="handleDelete">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-has-permi="['system:project:export']" icon="el-icon-download" plain size="mini" type="warning"
          @click="handleExport">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="ID" prop="id" width="40" />
      <el-table-column align="center" label="项目经理" prop="managerName" />
      <el-table-column align="center" label="名称" prop="name" />
      <el-table-column align="center" label="类别" prop="category">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.moe_project_category" :value="scope.row.category" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="级别" prop="level">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.moe_project_level" :value="scope.row.level" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="开始时间" prop="startTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="截止时间" prop="endTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="项目状态" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.moe_project_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="项目进度" width="120">
        <template slot-scope="scope">
          <el-progress :percentage="scope.row.proportion ? parseInt(scope.row.proportion / 100) : 0" :stroke-width="20"
            :text-inside="true" />
        </template>
      </el-table-column>
      <el-table-column label="项目信息" width="200">
        <template slot-scope="scope">
          <el-button v-has-permi="['system:project:query']" icon="el-icon-tickets" size="mini" type="text">
            <router-link :to="{ path: '/project/task', query: { id: scope.row.id } }" class="link-type" nonce="">
              <span>任务</span>
            </router-link>
          </el-button>
          <el-button v-has-permi="['system:project:query']" icon="el-icon-view" size="mini" type="text"
            @click="ProjectInfo(scope.row)">详情
          </el-button>
          <el-button v-has-permi="['system:project:edit']" icon="el-icon-sort" size="mini" type="text"
            @click="submitDialog(scope.row)">提交
          </el-button>
          <!-- 弹窗提示 -->
          <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
            <span>{{ dialogContent }}</span>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false"> 取 消 </el-button>
              <el-button type="primary" @click="submitNoFinish">确 定</el-button>
            </span>
          </el-dialog>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-has-permi="['system:project:edit']" icon="el-icon-edit" size="mini" type="text"
            @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-has-permi="['system:project:remove']" icon="el-icon-delete" size="mini" type="text"
            @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
      @pagination="getList" />

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目经理" prop="managerId">
          <el-select v-model="form.managerId" placeholder="请选择项目经理">
            <el-option v-for="   user    in    userList   " :key="user.userId" :label="user.nickName"
              :value="parseInt(user.userId)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择类别">
            <el-option v-for="   dict    in    dict.type.moe_project_category   " :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="form.level" placeholder="请选择级别">
            <el-option v-for="   dict    in    dict.type.moe_project_level   " :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" :picker-options="pickerStart" clearable placeholder="请选择开始时间"
            type="date" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker v-model="form.endTime" :picker-options="pickerEnd" clearable placeholder="请选择截止时间" type="date"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批理由" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 项目详情 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目经理" prop="managerId">
          <el-select v-model="form.managerId" placeholder="请选择项目经理" :disabled="true">
            <el-option v-for="   dict    in    dict.type.sys_user_sex   " :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" :disabled="true" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择类别" :disabled="true">
            <el-option v-for="   dict    in    dict.type.moe_project_category   " :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="级别" prop="level">
          <el-select v-model="form.level" placeholder="请选择级别" :disabled="true">
            <el-option v-for="   dict    in    dict.type.moe_project_level   " :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" :disabled="true" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" :disabled="true" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择截止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime">
          <el-date-picker clearable v-model="form.finishTime" :disabled="true" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择项目状态" :disabled="true">
            <el-option v-for="   dict    in    dict.type.moe_project_status   " :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" :disabled="true" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" :disabled="true" />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { addProject, delProject, getProject, listProject, submitProject, updateProject } from "@/api/system/project";
import { EventBus } from '@/event-bus.js'
import { listUserByRole } from "@/api/system/user";
import { mapMutations } from 'vuex'

export default {
  name: "Project",
  dicts: ['moe_project_category', 'moe_project_status', 'moe_project_level'],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 项目经理数据
      userList: [],
      dialogVisible: false,
      dialogContent: '',
      diallogId: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否弹窗详情
      openInfo: false,
      percentage: 0,
      // 是否显示项目经理
      isProjectAdmin: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        managerId: null,
        name: null,
        category: null,
        level: null,
        startTime: null,
        endTime: null,
        status: null,
      },
      queryUserListByRoleParams: {
        roleId: 11
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        managerId: [
          { required: true, message: "项目经理不能为空", trigger: "change" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        category: [
          { required: true, message: "类别不能为空", trigger: "change" }
        ],
        level: [
          { required: true, message: "级别不能为空", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "截止时间不能为空", trigger: "blur" }
        ]
      },
      pickerEnd: {
        disabledDate: (time) => {
          if (this.form.startTime) {
            return time.getTime() < new Date(this.form.startTime).getTime()
          } else {
            return false
          }
        }
      },
      pickerStart: {
      }
    };
  },
  created () {
    this.fundPower()
    this.getList();
    this.getUserListByRole();
  },
  methods: {
    ...mapMutations(['getCurrenTotal']),
    // 弹窗显示
    submitDialog (row) {

      this.dialogVisible = false
      if (row.status == '1') {
        this.dialogContent = '请重新修改后再提交'
        this.dialogVisible = true
        return
      }
      if ((row.proportion / 100) < 100 && row.status == '4' || row.proportion == null && row.status == '4') {
        this.dialogContent = '任务尚未完成，是否确认提交'
        this.dialogId = row.id
        this.dialogVisible = true
        return
      }
      this.ProjectSubmit(row.id)
    },

    // 任务未完成，仍提交
    submitNoFinish () {
      this.ProjectSubmit(this.dialogId)
      this.dialogVisible = false
    },
    // 项目经理选择按钮
    fundPower () {
      // 获取当前登录的角色id
      let roleRole = localStorage.getItem('currentRole')
      if (roleRole === 'project-admin') {
        this.isProjectAdmin = true
      }
      if (roleRole === 'project-manager') {
        this.isProjectAdmin = false
      }
    },
    /**项目提交 */
    ProjectSubmit (id) {

      submitProject(id).then(response => {

        if (response.code === 200) {
          this.$modal.msgSuccess(response.msg);
          EventBus.$emit('my-event')
        } else {
          this.$modal.msgWarning(response.msg);
        }
        this.getList()
      })
    },
    /** 查询项目列表 */
    getList () {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户列表根据角色 */
    getUserListByRole () {
      this.loading = true;
      listUserByRole(this.queryUserListByRoleParams).then(response => {
        this.userList = response.rows;
        this.loading = false;
      });
    },
    // 项目的详情信息
    ProjectInfo (row) {
      const id = row.id || this.ids
      getProject(id).then(response => {
        this.form = response.data;
        this.openInfo = true
        this.title = "项目详情";
      });
    },
    /** 项目下的子任务 */
    PushProjectInfo (row) {
      this.$router.push({ path: '/project/task', query: { id: row.id } })
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        managerId: null,
        managerName: null,
        name: null,
        category: null,
        level: null,
        startTime: null,
        endTime: null,
        finishTime: null,
        status: null,
        remark: null,
        description: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加项目";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      if (row.status === "0") {// 已审批、已通过
        this.$modal.msgWarning("该项目已验收，无法继续修改");
      } else if (row.status === "2") {// 已审批、未通过
        this.$modal.msgWarning("该项目等待验收，暂不支持修改");
      } else if (row.status === "3") {// 已结束
        this.$modal.msgWarning("该项目已结束，无法继续修改");
      } else {
        this.reset();
        const id = row.id || this.ids
        getProject(id).then(response => {
          this.form = response.data;

          this.open = true;

          this.title = "修改项目";

        });
      }
      this.getList();
    },
    /** 提交按钮 */
    submitForm () {
      this.dialogVisible = false
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {

            if (this.form.status == '1') {
              this.form.status = '4'
            }

            updateProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();

            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除项目编号为"' + ids + '"的数据项，包括与之关联的其他数据项？').then(function () {
        return delProject(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
